// grid和布局的全局变量
var sm;
var cm;
var store;
var grid;
var viewport;
var currentRowInd = 0;
var currentColInd;
var Plant;
Ext.onReady(function() {
	Ext.QuickTips.init();
	var sm = new Ext.grid.CheckboxSelectionModel();
	cm = new Ext.grid.ColumnModel([ new Ext.grid.RowNumberer(), sm, {
		header : 'id',
		dataIndex : 'id',
		hidden : true,
		width : 10
	}, {
		header : '查询列',
		dataIndex : 'columnName',
		editor : new Ext.form.TextField({
			allowBlank : false,
			blankText : "不允许为空"
		}),
		width : 120
	}, {
		header : '标题',
		dataIndex : "title",
		menuDisabled : true,
		width : 150,
		editor : new Ext.form.TextField()
	}, {
		header : '查询条件',
		dataIndex : "where",
		menuDisabled : true,
		editor :  new Ext.form.ComboBox({
            fieldLabel : '',
            store : new Ext.data.SimpleStore({
            	 data:[['=','='],['>','>'],['<','<'],['!=','!='],['>=','>='],['<=','<='],['like','like']],
        			fields:['SELECT_TITLE','SELECT_VALUE']
         }),
            valueField : 'SELECT_VALUE',
            displayField : 'SELECT_TITLE',
            triggerAction : 'all',
            selectOnFocus : false,
            editable: false,
            readOnly : false,
            allowBlank:false,
            mode : "local",
            emptyText : '请选择...'
      }),
		width : 100
	}, {
		header : '查询UI',
		dataIndex : "uiType",
		renderer : renderer_ui,
		width : 120
	}, {
		header : '自定义UI',
		dataIndex : "customHtml",
		menuDisabled : true,
		width : 300,
		editor : new Ext.form.TextField()
	}, {
		header : 'uiParam',
		dataIndex : "uiParam",
		hidden : true,
		width : 20
	}, {
		header : 'orderIndex',
		dataIndex : 'orderIndex',
		hidden : true,
		width : 80
	} ]);
	Plant = Ext.data.Record.create([ {
		name : 'id',
		type : 'string'
	}, {
		name : 'columnName',
		type : 'string'
	}, {
		name : 'title',
		type : 'string'
	}, {
		name : 'where',
		type : 'string'
	}, {
		name : 'uiType',
		type : 'string'
	}, {
		name : 'uiParam',
		type : 'string'
	}, {
		name : 'orderIndex',
		type : "int"
	} , {
		name : 'customHtml',
		type : "string"
	}]);

	store = new Ext.data.Store({
		baseParams : {
			id : id
		},
		proxy : new Ext.data.HttpProxy({
			url : basePath + 'repository/worklist/searchs/getWorkListSearchsJson'
		}),
		reader : new Ext.data.JsonReader({
			totalProperty : "total",
			root : "root",
			id : "id"
		}, [ 'id', 'title', 'columnName', 'where', 'uiType','uiParam', 'orderIndex','customHtml' ], Plant)
	});
	grid = new Ext.grid.EditorGridPanel({
		renderTo : 'grid',
		store : store,
		region : 'center',
		cm : cm,
		sm : sm,
		trackMouseOver : false,
		clicksToEdit : 1,
		loadMask : {
			msg : '正在加载数据，请稍候...'
		},
		border : false,
		enableDragDrop : true,
		viewConfig : {
			forceFit : true
		},
		listeners : {
			'bodyscroll' : function() {
				return false;
			}
		},
		tbar : [ {
			text : '添加',
			iconCls : 'iconNew',
			handler : function() {
				var insertRowInd = store.data.length;
				var Plant = grid.getStore().recordType;
				var p = new Plant({});
				p.set('id', '');
				p.set('title', '');
				p.set('columnName', '');
				p.set('where', '=');
				p.set('uiType', '单行');
				p.set('orderIndex', 0);
				grid.stopEditing();
				store.insert(insertRowInd, p);
				grid.startEditing(insertRowInd, 3);
			}
		}, '-', {
			text : '保存',
			iconCls : 'iconSave',
			handler : function() {
				saveGrid();
			}
		}, '-', {
			text : '删除',
			iconCls : 'iconDelete',
			id : "deleteC",
			disabled : true,
			handler : function() {
				remove();
			}
		}, '-', {
			text : '刷新',
			tooltip : '刷新',
			handler : function() {
				store.reload();
			},
			iconCls : 'iconRefresh'
		}, '->' ]
	});
	viewport = new Ext.Viewport({
		layout : 'border',
		items : [ grid ]
	});
	store.load();
	grid.getSelectionModel().on('selectionchange', function(t) {
		Ext.getCmp("deleteC").setDisabled(t.getSelections().length === 0);
	});
	   var ddrow = new Ext.dd.DropTarget(grid.container, {
	        ddGroup : 'GridDD',
	        copy    : false,
	        notifyDrop: function(dd, e, data) {
	        	       var rows = data.selections;
	        	       //data.rowIndex
	        	       //var index = dd.getDragData(e).rowIndex;
	        	       if(dd.getDragData(e).rowIndex==undefined ){
	        	       	  return;
	        	       	}
	        	       var  sourceId = rows[0].id;
	        	       var  targetId = dd.getDragData(e).selections[0].id;
	        	       handleSave(sourceId,targetId);
	        	       return;
	        	}
	     });
});
function saveGrid() {
	var m = store.getModifiedRecords();
	if (m.length > 0) {
		for (var i = 0, len = m.length; i < len; i++) {
			var rec = m[i];
		}
		var temp = 0;
		var json = [];
		Ext.each(m, function(item) {
			json.push(item.data);
		});
		store.commitChanges();
		Ext.Ajax.request({
			url : basePath + 'repository/worklist/searchs/saveWorkListSearch',
			method : 'POST',
			params : {
				datas : Ext.util.JSON.encode(json),
				id : id
			},
			failure : function(response, options) {
				Ext.MessageBox.alert('操作失败', '操作失败！可能是网络超时！');
				return false;
			},
			success : function(response, options) {
				if (response.responseText == '1') {
					Ext.MessageBox.alert('提示', " 保 存 成 功! ");
					store.reload();
				} else if (response.responseText == '-1') {
					Ext.MessageBox.alert('提示', " 保 存 失 败! ");
					return false;
				}
			}
		});

	} else {
		Ext.MessageBox.alert('提示', '当前没有需要保存的记录!');
		return false;
	}
}

function remove() {
	var selectedKeys = grid.selModel.selections.keys;
	Ext.MessageBox.confirm('提示', '确定删除选定的字段?', function(btn) {
		if (btn == 'yes') {
			Ext.Ajax.request({
				url : basePath + 'repository/worklist/searchs/removeWorkListSearch',
				method : 'POST',
				params : {
					ids : selectedKeys,
					id : id
				},
				failure : function(response, options) {
					Ext.MessageBox.alert('操作失败', '操作失败！可能是网络超时！');
					return false;
				},
				success : function(response, options) {
					if (response.responseText == 'ok') {
						store.commitChanges();
						store.reload();
						Ext.MessageBox.alert('提示', " 删 除 成 功! ");
					}
				}
			});
		}

	});
}

function renderer_ui(value, cell, record, rowIndex, columnIndex, store) {
	var clolumnId = record.data.id;
	var column_title = record.data.column_title;
	var column_lable = record.data.column_lable;
	var uiType = record.data.uiType;
	var val = '<a href=\'javascript:void(0)\' onclick="changeUi('+rowIndex+');">' + uiType + '</a>';
	return val;
}
function settingUiComponentParams(uiRowIndex,uiType,uiParam){
	var record = grid.getStore().getAt(uiRowIndex);
	record.set('uiType',uiType);
	record.set('uiParam',uiParam);
	uiWindow.close();
}

var uiWindow;
function changeUi(uiRowIndex) {

	var uiTabs = new Ext.TabPanel({
		region : 'center',
		deferredRender : false,
		activeTab : 0,
		border : true
	});
	var uiRecord = grid.getStore().getAt(uiRowIndex);
	var id = uiRecord.data.id;
	var uiName = uiRecord.data.uiType;
	var uiParam = uiRecord.data.uiParam;
	var columnTitle = uiRecord.data.title;
	var clumnLabel = uiRecord.data.columnName;
	var curUiType = uiName;
	createViewTab("ui", uiName, "", "", true);
	var uiroot = new Ext.tree.TreeNode({
		id : 'uiRoot',
		text : 'ui',
		expanded : true
	});
	var danhang = new Ext.tree.AsyncTreeNode({
		id : 'danhang',
		text : '单行',
		cls : 'formUIComponent_text',
		leaf : true
	});
//	var shuzhi = new Ext.tree.AsyncTreeNode({
//		text : "数值",
//		leaf : true,
//		cls : 'formUIComponent_number',
//		id : 'shuzhi'
//	});
	var data = new Ext.tree.AsyncTreeNode({
		text : "日期",
		leaf : true,
		cls : 'formUIComponent_date',
		id : 'data'
	});
	var select = new Ext.tree.AsyncTreeNode({
		text : "列表",
		cls : 'formUIComponent_combox',
		leaf : true,
		id : 'select'
	});
	var datadic = new Ext.tree.AsyncTreeNode({
		text : "数据选择器",
		leaf : true,
		cls : 'formUIComponent_text',
		id : 'datadic'
	});
	var nonull = new Ext.tree.AsyncTreeNode({
		text : "无",
		leaf : true,
		cls : 'formUIComponent_text',
		id : 'nonull'
	});
	uiroot.appendChild(nonull);
	uiroot.appendChild(danhang);
//	uiroot.appendChild(shuzhi);
	uiroot.appendChild(data);
	uiroot.appendChild(select);
	uiroot.appendChild(datadic);
	var uiTree = new Ext.tree.TreePanel({
		title : "查询UI",
		id : "uiTree",
		region : 'west',
		width : 150,
		border : true, // 面板边框
		useArrows : false, // 箭头节点图标
		root : uiroot, // 根节点
		autoScroll : true, // 内容溢出时产生滚动条
		animate : false,
		rootVisible : false
	});
	uiTree.on('click', function(node) {
		var text = node.attributes.text;
		curUiType = text;
		createViewTab("ui", text, "", "", true);
	});
	uiWindow = new Ext.Window({
		title : '' + columnTitle + '(' + clumnLabel + ')',
		id : "uiwindowid",
		width : 800,
		height : 450,
		modal : true,
		constrainHeader : true,
		plain : true,
		layout : 'border',
		items : [ uiTree, uiTabs ]
	});
	uiWindow.show();
	function createViewTab(tabId, tabTitle, iconClassName, htmlSrc, isRefresh) {
		tabId = 'tabs_' + tabId;
		var html = "<iframe id='Ui_Portal_Tab_Frame' name='Ui_Portal_Tab_Frame' src='' frameborder='0' scrolling=\"false\" width='100%' height='100%'  ></iframe>";
		var tab = uiTabs.getItem(tabId);
		if (tab == null) {
			tab = uiTabs.add({
				id : tabId,
				title : tabTitle,
				tabTip : tabTitle,
				closable : false,
				autoScroll : true,
				iconCls : iconClassName,
				tbar : [ {
					text : '确定',
					iconCls : 'iconSave',
					handler : function() {
						var curParams = Ui_Portal_Tab_Frame.getSettingParams();
						settingUiComponentParams(uiRowIndex, curUiType, curParams);
					}
				} ],
				html : html
			}).show();
			tab.addListener('show', function() {
				setTimeout(function() {
					document.getElementById('formForm').action = basePath + "/repository/worklist/searchs/getSettingPage";
					document.getElementById('uiType').value = curUiType;
					var curParams = curUiType == uiName ? uiParam : '';
					document.getElementById('uiParams').value = curParams;
					document.getElementById('formForm').target = 'Ui_Portal_Tab_Frame';
					document.getElementById('formForm').submit();
				}, 1000);
			});
		} else {
			if (isRefresh) {
				tab.setTitle(tabTitle);
			}
			tab.show();
		}

	}
}
function handleSave(sourceId,targetId){
	  Ext.getBody().mask("保存排序...");
	  Ext.Ajax.request({
				url : basePath+'repository/worklist/searchs/sortGird',
				method : 'POST',
				params : {
					 sourceId: sourceId,
					 targetId: targetId,
					 id:id
				},
				failure : function(response, options) {
					Ext.MessageBox.alert('操作失败', '操作失败！可能是网络超时！');
					return false;
				},
				success : function(response, options) {
					Ext.getBody().unmask();
					if(response.responseText!='1'){
						Ext.MessageBox.alert('提示', " 排序发生错误，请刷新重新重试! ");
					}else{
						store.load();
					}
				}
			});	  
	}
